package edu.gxmzu.task.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import edu.gxmzu.task.config.security.MyUserDetails;
import edu.gxmzu.task.entity.Accounts;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

public class ConvertMyUserDetailsUtil {

    // 从缓存中反序列化MyUserDetails
    public static MyUserDetails convert(Object object) {
        // 将 object 转换为 Map
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) object;
        // 反序列化 account
        Accounts account = JSON.parseObject(JSON.toJSONString(map.get("account")), Accounts.class);
        // 反序列化 permissions
        List<String> permissions = JSON.parseObject(JSON.toJSONString(map.get("permissions")), new TypeReference<List<String>>() {});
        // 反序列化 authorities
        List<LinkedHashMap<String, String>> authoritiesMap = JSON.parseObject(JSON.toJSONString(map.get("authorities")), new TypeReference<List<LinkedHashMap<String, String>>>() {});
        List<SimpleGrantedAuthority> authorities = authoritiesMap.stream()
                .map(authority -> new SimpleGrantedAuthority(authority.get("authority")))
                .collect(Collectors.toList());
        // 创建 MyUserDetails 对象
        MyUserDetails myUserDetails = new MyUserDetails(account, permissions);
        myUserDetails.setAuthorities(authorities);
        return myUserDetails;
    }
}
